const modal = document.getElementById('modal');
const closeBtn = document.getElementById('closeBtn');
const eventsUl = document.querySelector('#event ul');

const eventModal = document.getElementById('eventModal');
const eventCloseBtn = document.getElementById('eventCloseBtn');

let calendarEvents = [];
const form = {
  id: '',
  title: '',
  des: '',
  date: ''
}

// 新增/修改
const eventDate = document.getElementById('eventDate');
const eventTitle = document.getElementById('eventTitle');
const eventDesc = document.getElementById('eventDesc');
const sureButton = document.getElementById('sureButton');

const lddyClick = document.querySelector('#lddyClick');
let isLddy = false;

function showModal(dom) {
  dom.classList.add('active');
  if (form.id) {
    eventDate.value = form.date;
    eventTitle.value = form.title;
    eventDesc.value = form.des;
  } else {
    eventDate.value = '';
    eventTitle.value = '';
    eventDesc.value = '';
  }
}

function closeModal(dom) {
  dom.classList.remove('active');
}

async function getCalendarEvents() {
  eventsUl.innerHTML = '';
	const res = await fetch('http://1.95.157.217/api/lindadayo/getCalendarEvents', {
		method: 'GET'
	}).then(response => {
		if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
		}
		return response.json();
  })
	if (res.code === 0) {
		calendarEvents = res.data.map((item => {
      const li = document.createElement('li');
      li.className = 'timeline-item';
      const time = document.createElement('div');
      time.className = 'timeline-date';
      time.textContent = item.date;
      li.appendChild(time);

      const content = document.createElement('div');
      content.className = 'timeline-content';
      li.appendChild(content);
    
      const title = document.createElement('div');
      title.className = 'timeline-title';
      title.textContent = item.title;
      content.appendChild(title);

      const edit = document.createElement('div');
      edit.className = 'edit';
      content.appendChild(edit);
      edit.addEventListener('click', () => {
        form.id = item.id;
        form.title = item.title;
        form.des = item.des;
        form.date = item.date;
        showModal(eventModal)
      })

      const des = document.createElement('div');
      des.className = 'timeline-des';
      des.textContent = item.des;
      content.appendChild(des);

      const add = document.createElement('div');
      add.className = 'add';
      li.appendChild(add);
      add.addEventListener('click', () => {
        form.id = '';
        form.title = '';
        form.des = '';
        form.date = '';
        showModal(eventModal)
      })

      eventsUl.appendChild(li)
      li.addEventListener('click', () => {
        const date = new Date(item.date);
        calendar.navTo(date)
      })
      return item;
    }))
    setTimeout(() => {
      calendar.renderDay();
    }, 500);
	}
}
/**
 * 新增日历事件
 */
async function addCalendarEvent() {
  const res = await fetch('http://1.95.157.217/api/lindadayo/addCalendarEvent', {
		method: 'POST',
    body: JSON.stringify({
      ...form,
      owner: isLddy ? '小林' : '瑶瑶'
    }),
    headers: {
      'Content-Type': 'application/json'
    }
	}).then(response => {
		if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
		}
    closeModal(eventModal);
		getCalendarEvents();
  })
}``
/**
 * 更新日历事件
 */
async function updateCalendarEvent() {
  if (!isLddy && (form.id === 8 || form.title.indexOf('乐山') !== -1)) {
    alert('抱歉这条不允许修改！');
    return;
  }
  const res = await fetch('http://1.95.157.217/api/lindadayo/updateCalendarEvent', {
		method: 'POST',
    body: JSON.stringify({
      ...form,
      owner: isLddy ? '小林' : '瑶瑶'
    }),
    headers: {
      'Content-Type': 'application/json'
    }
	}).then(response => {
		if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
		}
    closeModal(eventModal);
		getCalendarEvents();
  })
}
const calendar = new Calendar();
calendar.initCalendar(new Date('2024-08-21'))
getCalendarEvents();

closeBtn.addEventListener('click', () => {
  closeModal(closeBtn);
})

eventCloseBtn.addEventListener('click', () => {
  closeModal(eventModal);
})

function formatDate(dateStr) {
  const date = new Date(dateStr);
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    throw new Error('无效日期格式');
  }
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
}

sureButton.addEventListener('click', () => {
  try {
    form.date = formatDate(eventDate.value);
    form.title = eventTitle.value;
    form.des = eventDesc.value;
    if (form.id) {
      updateCalendarEvent();
    } else {
      addCalendarEvent();
    }
  } catch (e) {
    alert(e)
  }
})

lddyClick.addEventListener('click', () => {
  isLddy = true;
})